package leetcode_top;

import java.util.Arrays;

import org.junit.Test;

public class Ex26 {
    class Solution {
        //原地删除数组重复元素重复
        /* 
            先遍历一遍，找到不重复的元素个数n，作为返回值
            从右往左，依次将不重复的元素作为当前可见数组(初始长度为n)最后一个元素，并且长度减一，直到为0
        */
        public int removeDuplicates(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            int len = nums.length, last = nums[0], count = 1;
            for (int i = 1; i < len; i++) {
                if (nums[i] != last) {
                    count++;
                    last = nums[i];
                }
            }
            last = nums[0];
            int idx = 0;
            nums[idx++] = last;
           for (int i = 1; i < len; i++) {
                if (nums[i] != last) {
                    nums[idx++] = nums[i];
                    last = nums[i];
                }
                if (idx == count) break;
            }
            return count;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        int[] nums = new int[]{0,0,1,1,1,2,2,3,3,4 };
        System.out.println(s.removeDuplicates(nums));
        System.out.println(Arrays.toString(nums));
    }
}
